package com.vegetable.modules.service.finance.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.constant.CommonConstant;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.common.utils.Query;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.baseData.AddressBook;
import com.vegetable.modules.entity.finance.PaymentTeam;
import com.vegetable.modules.entity.finance.PaymentTeamDetail;
import com.vegetable.modules.entity.inbound.PackDelivery;
import com.vegetable.modules.mapper.finance.PaymentTeamMapper;
import com.vegetable.modules.service.baseData.IAccountDetailsService;
import com.vegetable.modules.service.baseData.IAddressBookService;
import com.vegetable.modules.service.baseData.IFundAccountService;
import com.vegetable.modules.service.finance.IPaymentTeamDetailService;
import com.vegetable.modules.service.finance.IPaymentTeamService;
import com.vegetable.modules.service.inbound.IPackDeliveryService;
import com.vegetable.modules.service.inbound.IPackDeliveryTeamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 班组付款 服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-04-15
 */
@Slf4j
@Service
public class PaymentTeamServiceImpl extends ServiceImpl<PaymentTeamMapper, PaymentTeam> implements IPaymentTeamService {
    @Resource
    // 通讯录
    private IAddressBookService addressBookService;
    @Resource
    private IFundAccountService accountService;
    @Resource
    private IAccountDetailsService iAccountDetailsService;
    @Resource
    private IPaymentTeamDetailService iPaymentTeamDetailService;
    @Resource
    private IPackDeliveryService iPackDeliveryService;

    private IPackDeliveryTeamService iPackDeliveryTeamService;

    /**
     * 班组付款列表查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String docNo = (String)params.get("docNo");
        String startTime = (String)params.get("startTime");
        String endTime = (String)params.get("endTime");
        IPage<PaymentTeam> page = this.page(
                new Query<PaymentTeam>().getPage(params),
                new QueryWrapper<PaymentTeam>()
                        .between(StringUtils.isNotBlank(startTime), "create_time", startTime + " 00:00:00", endTime +" 23:59:59")
                        .eq(ObjectUtils.isNotEmpty(params.get("teamId")),"team_id", params.get("teamId"))
                        .like(StringUtils.isNotBlank(docNo),"doc_no", docNo)
                        .orderByDesc("create_time")
        );
        List<PaymentTeam> ptList = page.getRecords();
        if(CollectionUtil.isNotEmpty(ptList)){
            List<Long> ptIds = ptList.stream().map(el -> el.getId()).collect(Collectors.toList());
            List<PaymentTeamDetail> details = iPaymentTeamDetailService.queryByMainIds(ptIds);
            List<String> packIds = details.stream().map(el -> el.getDocNo()).collect(Collectors.toList());
            List<PackDelivery> packDeliveryList = iPackDeliveryService.selectByDocNoList(packIds);
            for(PaymentTeamDetail ptd : details){
                PackDelivery pd = packDeliveryList.stream().filter(el -> el.getDocNo().equals(ptd.getDocNo())).findAny().orElse(null);
                if(ObjectUtil.isNotNull(pd)){
                    ptd.setCommodityName(pd.getFinishCommodityName());
                    ptd.setPlanWeight(pd.getFinishWeight());
                    ptd.setPlanNumber(pd.getFinishNumber());
                }
            }
            Map<Long, List<PaymentTeamDetail>> areaMap = details.stream().collect(Collectors.groupingBy(PaymentTeamDetail::getMainId));
            for(PaymentTeam pt : ptList){
                List<PaymentTeamDetail> valueList = areaMap.get(pt.getId());
                pt.setPayDetails(valueList);
            }
        }
        return new PageUtils(page);
    }

    /**
     * 新增班组付款
     * @param order null
     * @return R
     * @author wrj
     * @since 2024/3/7 下午4:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveTeamPayment(PaymentTeam order) throws Exception {
        List<PaymentTeamDetail> payDetails = order.getPayDetails();
        if(CollectionUtil.isEmpty(payDetails)){
            return R.fail("付款明细不能为空");
        }
        if (order.getId() == null){
            order.setDocNo(CommonConstant.BZFK+ baseMapper.getNextCode());
        }
        BigDecimal totalMoney = payDetails.stream().map(PaymentTeamDetail::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        order.setMoney(totalMoney);
        // todo 不再统计流水信息
//        accountService.addReceipts(order.getAccountId(), order.getMoney(), Constant.MoneyTYPE.TEAM_OUT, order.getDocNo(), order.getId(), order.getTeamName());
        updateArrears(order.getTeamId(), totalMoney, false);
        this.saveOrUpdate(order);


        for (PaymentTeamDetail detail : payDetails) {
            detail.setMainId(order.getId());
        }
        iPaymentTeamDetailService.saveBatch(payDetails);
//        List<AccountDetails> adList = new ArrayList<>();
//        for (PaymentTeamDetail detail : payDetails) {
//            AccountDetails ad = new AccountDetails();
//            ad.setId(detail.getOrderId());
//            ad.setIsPayFinish(1);
//            adList.add(ad);
//        }
        iPackDeliveryTeamService.packFinishPay(payDetails);
        return R.status(true);
    }

    /**
     * 更新客商的应收金额
     *
     * @param money null
     * @return void
     * @author wrj
     * @since 2024/3/22 上午11:47
     */
    private void updateArrears(Long teamId, BigDecimal money, boolean addFlag){
        // 更新待办的应收金额
        AddressBook addressBook = addressBookService.getById(teamId);
        BigDecimal arrears = addressBook.getArrears();
        if (addFlag){
            // 加上该订单代办应收金额
            arrears = arrears.add(money);
        }else {
            // 减去该订单代办应收金额
            arrears = arrears.subtract(money);
        }
        addressBook.setArrears(arrears);
        addressBookService.updateById(addressBook);
    }
    /**
     * 删除班组付款
     * @param id null
     * @return R
     * @author wrj
     * @since 2024/3/7 下午4:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteTeam(Long id) throws Exception {
        PaymentTeam order = baseMapper.selectById(id);
        if (order == null){
            throw new Exception("班组付款不存在");
        }
        // 更新总支出 回退
//        FundAccount account_out = accountService.getById(order.getAccountId());
//        if (account_out != null){
//            BigDecimal totalExpenditure = account_out.getTotalExpenditure();
//            totalExpenditure = totalExpenditure.subtract(order.getMoney());
//            account_out.setTotalExpenditure(totalExpenditure);
//            accountService.updateById(account_out);
//        }

        updateArrears(order.getTeamId(), order.getMoney(), true);
        baseMapper.deleteById(id);
        return R.status(true);
    }
}
